package com.itwxz.common.utils;

import cn.hutool.core.util.RandomUtil;
import com.itwxz.common.config.MailConfig;
import com.itwxz.common.constant.CacheConstants;
import com.itwxz.common.constant.Constants;
import com.itwxz.common.core.domain.MailAccount;
import com.itwxz.common.core.redis.RedisCache;
import com.itwxz.common.utils.uuid.IdUtils;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MailSenderUtils {
	@Autowired
	private RedisCache redisCache;

	private final List<JavaMailSenderImpl> senderList = new ArrayList<>();
	// 获取随机一个 JavaMailSenderImpl
	private JavaMailSenderImpl getRandomSender() {
		return senderList.get(RandomUtil.randomInt(0, senderList.size()));
	}

	public MailSenderUtils(MailConfig config) {
		for (MailAccount account : config.getAccounts()) {
			JavaMailSenderImpl sender = new JavaMailSenderImpl();
			sender.setHost(account.getHost());
			sender.setPort(account.getPort());
			sender.setUsername(account.getUsername());
			sender.setPassword(account.getPassword());

			Properties props = sender.getJavaMailProperties();
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.enable", "true");

			senderList.add(sender);
		}
	}


	/**
	 * 发送简单文本邮件
	 */
	public void sendSimpleMail(String to, String subject, String content) {
		JavaMailSenderImpl sender = getRandomSender();
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(sender.getUsername());
		message.setTo(to);
		message.setSubject(subject + "#义务维修协会");
		message.setText(content);
		sender.send(message);
	}

	/**
	 * 发送 HTML 邮件
	 */
	public void sendHtmlMail(String to, String subject, String htmlContent) throws MessagingException {
		JavaMailSenderImpl sender = getRandomSender();
		MimeMessage message = sender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

		if (sender.getUsername() != null) helper.setFrom(sender.getUsername());

		helper.setTo(to);
		helper.setSubject(subject + "#义务维修协会");
		helper.setText(htmlContent, true); // 第二个参数 true 表示 HTML

		sender.send(message);
	}


	/**
	 * 发送验证码邮件
	 */
	public String sendVerifyCodeMail(String to) {
		// 生成4位数字+字母混合验证码
		String code = RandomUtil.randomString(4);
		// 保存验证码信息
		String uuid = IdUtils.simpleUUID();
		String eVerifyKey = CacheConstants.EMAIL_CODE_KEY + uuid;
		redisCache.setCacheObject(eVerifyKey, code, Constants.EMAIL_EXPIRATION, TimeUnit.MINUTES);

		String subject = "邮箱验证";
		String content = "<div style=\"font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 400px; margin: 0 auto; padding: 24px; border-radius: 8px; background: #f9f9f9; border: 1px solid #eee;\">" +
				"<h2 style=\"color: #2d8cf0;\">您的验证码</h2>" +
				"<p style=\"font-size: 16px; color: #333;\">您好，感谢您的操作！</p>" +
				"<p style=\"font-size: 16px; color: #333;\">您的验证码是：</p>" +
				"<div style=\"font-size: 28px; font-weight: bold; color: #2d8cf0; letter-spacing: 4px; margin: 16px 0;\">" + code + "</div>" +
				"<p style=\"font-size: 14px; color: #888;\">有效期5分钟。如非本人操作请忽略本邮件。</p>" +
				"<div style=\"margin-top: 24px; font-size: 12px; color: #bbb;\">—— 义务维修协会</div>" +
				"</div>";

		try {
			sendHtmlMail(to, subject, content);
		}catch (MessagingException e) {
			log.error(e.getMessage());
		}

		return uuid;
	}

	/**
	 * 发送订单未完成提醒邮件
	 */
	public void sendOrderReminderMail(String to, String staffName, String orderIds, int orderCount) {
		String subject = "订单未完成提醒";
		String content = String.format(
				"<div style='font-family: Arial, sans-serif; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #eee; border-radius: 8px; background: #fafafa;'>"
						+ "<h2 style='color: #2d8cf0;'>亲爱的 %s 同学</h2>"
						+ "<p>您目前有 <strong>%d</strong> 个订单尚未完成。</p>"
						+ "<p>订单编号如下：</p>"
						+ "<p style='color: #ff4d4f; font-size: 16px;'>%s</p>"
						+ "<p>请尽快处理。</p>"
						+ "<br><p style='font-size: 12px; color: #999;text-align: right;'>—— 义务维修协会</p>"
						+ "</div>",
				staffName == null ? "" : staffName,
				orderCount,
				orderIds
		);

		try {
			sendHtmlMail(to, subject, content);
		} catch (MessagingException e) {
			log.error("发送订单提醒邮件失败: {}", e.getMessage(), e);
		}
	}


}
